package gw.com.android.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Date;
import java.util.Enumeration;
import java.util.LinkedHashMap;

import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.presenter.http.Https;
import gw.com.android.ui.onlive.analyst.AnalystRequest;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.app.AppActivities;
import www.com.library.app.AppContances;
import www.com.library.app.Logger;
import www.com.library.util.DeviceUtil;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.PermissionUtil;

/**
 * Created by spence on 17-7-18.
 */

public class PackStatis {

    private final static String logType = "3";//日志类型 1：网站 2：直播间 3:APP
    private final static String deviceId = DeviceUtil.instance().getMacAddr(AppMain.getApp());//设备唯一标识
    private final static String deviceType = "Android";//设备(终端)类型:Android,IOS,PCUI
    private final static String platformType = "GTS2";//账户平台／应用名称：
    private final static String accountType = "";
    private static String channel = "default"; //渠道名称
    private final static String model = DeviceUtil.instance().getDeviceModel();//设备型号，如iphone 6s
    private static String userIp = null;
    private static String deviceResolution = DeviceUtil.instance().getScreenDpWidth(
            AppActivities.getSingleton().currentActivity()) + "*" + DeviceUtil.instance().getScreenDpHeight(AppActivities.getSingleton().currentActivity());//屏幕分辨率
    private static String platformVersion = DeviceUtil.instance().appVersionName(AppActivities.getSingleton().currentActivity());//app版本号
    private final static String carrier = DeviceUtil.instance().getDeviceManufacturer();//设备厂商，如xiaomi  huawei
    private static String platformName = "gts2";
    private static String businessplatform = "3";

    public enum EventCategory {
        MAIN("Main"),//App 全局
        HOME("Home"),//首页页面
        CIRCLE("Circle"),
        ME("Me"),//我页面
        MESSAGE("Message"),//消息中心及详情
        ACCOUNTINFO("AccountInfo"),//个人信息
        MARKET("Market"),//行情
        SEARCH("Search"),//搜索
        SETTING("Setting"),//设置
        TRADE("Trade"),//交易
        LOGIN("login");//登录
        String value;

        EventCategory(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }

    public enum EventAction {
        START("Start"),//启动App
        CLICKPUSH("clickPush"),//点击推送
        CLICKTABBAR("clickTabbar"),//点击底部标签
        CLICKBANNER("click_banner_home"),//点击头部Banner
        CLICKMIDDLEBANNER("clickunadvert"),//点击中间广告位
        CLICKPRODUCT("ClickProduct"),//点击行情//点击产品名称
        CLICKPRODUCTEDIT("ClickProductEdit"),//点击行情处的编辑自选
        CLICKICON("ClickIcon"),//点击行情下方的Icon
        CLICKTALK("ClickTalk"),//点击单条讨论
        CLICKTALKGOOD("ClickTalkGood"),//点击单挑讨论的“赞”
        CLICKTALKWANTSHOW("ClickTalkWantShow"),//点击“我要晒单”
        CLICKTALKMORE("ClickTalkMore"),//点击“点击进入热门讨论”
        CLICKREG("clickReg"),//点击“登录／注册”//点击登录/注册（仅游客可用
        CLICKSETTING("ClickSetting"),//点击设置
        CLICKACCOUNT("ClickAccount"),//点击账号（仅真实可用
        CLICKEYE("ClickEye"),//点击眼睛
        CLICKLOGIN("clickLogin"),//点击登录
        CLICKINCOME("clickIncome"),//点击存款
        CLICKOUTCOME("clickOutcome"),//点击取款
        CLICKACCOUNTINFO("ClickAccountInfo"),//点击个人信息
        CLICKREWARD("ClickReward"),//点击推荐有奖
        CLICKCOLLECTION("ClickCollection"),//点击收藏订阅
        CLICKNEWS("ClickNews"),//点击消息中心
        CLICKCONTACT("ClickContact"),//点击联系我们
        CLICKMESSAGE("ClickMessage"),//点击单条消息
        CLICKMESSAGELINK("ClickMessageLink"),//点击单条消息内的链接地址
        CLICKSELFINFO("ClickSelfInfo"),//点击个人资料
        CLICKBACKINFO("clickBankInfo"),//点击银行资料
        CLICKUPDATEINFO("ClickUpdateInfo"),//点击资料上传
        CLICK("Click"),//点击版块
        CLICKADD1("ClickAdd1"),//点击右上角＋增加自选产品
        CLICKPRODUCTBUY("ClickProductBuy"),//点击买入价
        CLICKPRODUCTSELL("ClickProductSell"),//点击卖出价
        CLICKCHANGESORT("ClickChangeSort"),//点击切换涨跌幅
        CLICKADD2("ClickAdd2"),//点击“＋添加自选”
        CLICKCHANGE("ClickChange"),//点击真实模拟切换按钮
        CLICKCHANGETODEMO("ClickChangeToDemo"),//真实账户点击模拟
        CLICKCHANGETOREAL("ClickChangeToReal"),//模拟账户点击真实
        CLICKREGBY("ClickRegBy"),//游客点击开户
        CLICKREGBYDEMO("ClickRegByDemo"),//模拟账户点击开户
        CLICKMONEYSAVE("ClickMoneySave"),//真实账户点击存款
        LOADING("Loading"),//加载搜索页面
        CLICKINPUT("ClickInput"),//点击输入框
        CLICKRESULTADD("ClickResultAdd"),//对搜索出来的产品点击＋
        CLICKRESULT("ClickResult"),//点击搜索出来的产品
        CLICKDELETEALL("ClickDeleteAll"),//点击清除记录
        CLICKCHANGEPASSWORD("ClickChangePassword"),//点击修改密码
        CLICKAUTOLOGIN("ClickAutoLogin"),//点击自动为我登录开关
        CLICKLANGUAGE("ClickLanguage"),//点击系统语言
        CLICKTIMEZONE("ClickTimeZone"),//点击系统时区
        CLICKALWAYSLIGHT("ClickAlwaysLight"),//屏幕常亮开关
        CLICKCOLORTYPE("ClickColorType"),//点击显示设置
        CLICKVOICE("ClickVoice"),//点击声音设置
        CLICKCLEAR("ClickClear"),//点击清除缓存
        CLICKABOUTUS("ClickAboutUs"),//点击关于我们
        CLICKLOGOUT("ClickLogout"),//点击退出登录
        QUIT("Quit"),//退出App
        LOGIN("Login"),//客户完成帐户登录时上报
        LOGOUT("Logout"),//客户帐户退出登录时上报
        BUY("Buy"),//完成开仓时上报
        SELL("Sell"),//完成平仓时上报
        CLICKSEARCH("ClickSearch"),//点击搜索

        // 2017-11-8 1.6.1
        CLICKSERVICE("clickservice"),//点击右上角的耳麦标识联系客服
        CLICKREMIND("clickMessage"),//点击右上角的耳麦标识联系客服
        CLICKBROADCAST("clickbroadcast"),//点击实时解盘中的正在播放
        CLICKRADIO("clickradio"),//点击恒信语言播报按钮
        CLICKHELP("clickhelp"),//点击截屏之后弹出的求助反馈
        CLICKSHARE("clickshare"),//点击截屏之后弹出的分享
        CLICKRACCOUNT("clickRaccount"),//点击"我页面"的开真实账户
        CLICKNACCOUNT("clickNaccount"),//点击登录页面的开户按钮
        CLICKPROFITLIST1("clickProfitList1"),//  点击，盈利榜
        CLICKPROFITLIST2("clickProfitList2")//  点击，盈利榜
        ;
        String value;

        EventAction(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }

    static LinkedHashMap<String, String> paramsMap = new LinkedHashMap<>();

    static {
        paramsMap.put("logType", logType);
        paramsMap.put("deviceId", deviceId);
        paramsMap.put("deviceType", deviceType);
        paramsMap.put("platformType", platformType);
        paramsMap.put("accountType", accountType);
        paramsMap.put("model", model);
        paramsMap.put("userIp", userIp);
        paramsMap.put("deviceResolution", deviceResolution);
        paramsMap.put("platformVersion", platformVersion);
        paramsMap.put("carrier", carrier);
    }

    public static void getToService(String eventAction, String eventCategory, String eventLabel, String eventValue) {
        String url = ConfigUtil.instance().getUrlPath(ConfigType.SOCKET_IO_TAG);
        String account = "";//用户帐号
        String userType; //用户类型（1.游客、2.模拟、3：真实(不确定有没有激活，由数据平台判断)）
        int accountTypeTemp = GTConfig.instance().getAccountType();
        if (accountTypeTemp == GTConfig.ACC_TYPE_GUEST) {
            userType = "1";
        } else if (accountTypeTemp == GTConfig.ACC_TYPE_DEMO) {
            userType = "2";
            account = GTConfig.instance().mCurName;
        } else {
            if ("".equals(GTConfig.instance().mCurName)) {
                userType = "1";
            } else {
                userType = "3";
            }
            account = GTConfig.instance().mCurName;
        }
        String netStatus = "";
        if (NetworkMonitor.getNetworkType(AppActivities.getSingleton().currentActivity()) == AppContances.NET_WORK_WIFI_TYPE) {
            netStatus = "wifi";
        } else if (NetworkMonitor.getNetworkType(AppActivities.getSingleton().currentActivity()) == AppContances.NET_WORK_MOBILE_TYPE) {
            netStatus = "mobile";
        }
        //String operationType = mOperationType;//操作类型 1：启动 、2：登陆 、3：交易、4：注销、5:退出、6：自定义事件
        userIp = getIPAddress(AppMain.getApp());//ip
        ChannelUtil channelUtil = new ChannelUtil();
        channel = channelUtil.getChannel(AppMain.getApp());
        platformName = ENV.getAppName() + AppMain.getApp().getPackageName();
        paramsMap.put("eventAction", eventAction);
        paramsMap.put("eventCategory", eventCategory);
        paramsMap.put("eventLabel", eventLabel);
        paramsMap.put("eventValue", eventValue);
        paramsMap.put("userType", userType);
        paramsMap.put("account", account);
        paramsMap.put("netStatus", netStatus);
        paramsMap.put("channel", channel);
        paramsMap.put("businessPlatform", businessplatform);
        paramsMap.put("platformName", platformName);
        paramsMap.put("AccountSessionID", GTConfig.instance().mSession);
        if (AppMain.getApp().hasReadPhone()) {
            paramsMap.put("idfa", DeviceUtil.instance().getIMEI(AppMain.getApp()));
        } else {
            PermissionUtil mPermission = new PermissionUtil();
            Activity activity = AppActivities.getSingleton().currentActivity();
            if (null == activity) {
                return;
            }
            mPermission.requestPermission(activity, Manifest.permission.READ_PHONE_STATE, gw.com.android.app.AppContances.REQUEST_PERMISSION_ACCESS_PHONE, new PermissionUtil.OnRequestPermissionResult() {
                @Override
                public void onGranted() {
                    paramsMap.put("idfa", DeviceUtil.instance().getIMEI(AppMain.getApp()));
                }

                @Override
                public void onRefused() {

                }
            });
        }
        String dates = new Date().getTime() + "& ";
        paramsMap.put("dates", dates);
        new Https(url).addParams(paramsMap).get(null);
        saveAppStat(userType, netStatus, eventAction, account,eventCategory,eventLabel,eventValue);
    }

    /**
     * app访问记录接口
     */
    public static void saveAppStat(String userType, String netStatus, String eventAction, String account,String eventCategory,String eventLabel,String eventvalue) {
        String url = "https://stat.ftww.com/index.php?s=/home/appstat/stat";
        //重新构建 参数 ;参考文档为 http://192.168.75.49:3010/index.php?s=/13&page_id=244
        final LinkedHashMap<String, String> tempMap = new LinkedHashMap<>();
        tempMap.put("device_id", deviceId);
        tempMap.put("logtype", logType);
        tempMap.put("usertype", userType);
        tempMap.put("platformtype", platformType);
        tempMap.put("platformname", platformName);
        tempMap.put("businessplatform", "18");
        tempMap.put("carrier", carrier);
        tempMap.put("model", model);
        tempMap.put("platformversion", platformVersion);
        tempMap.put("deviceresolution", deviceResolution);
        tempMap.put("netstatus", netStatus);

        //依照文档，再加3个参数
        tempMap.put("eventcategory", eventCategory);
        tempMap.put("eventlabel", eventLabel);
        tempMap.put("eventvalue", eventvalue);

        if (AppMain.getApp().hasReadPhone()) {
            tempMap.put("idfa", DeviceUtil.instance().getIMEI(AppMain.getApp()));
        } else {
            PermissionUtil mPermission = new PermissionUtil();
            Activity activity = AppActivities.getSingleton().currentActivity();
            if (null == activity) {
                return;
            }
            mPermission.requestPermission(activity, Manifest.permission.READ_PHONE_STATE, gw.com.android.app.AppContances.REQUEST_PERMISSION_ACCESS_PHONE, new PermissionUtil.OnRequestPermissionResult() {
                @Override
                public void onGranted() {
                    tempMap.put("idfa", DeviceUtil.instance().getIMEI(AppMain.getApp()));
                }

                @Override
                public void onRefused() {

                }
            });
        }

        tempMap.put("even_name", eventAction);
        tempMap.put("location_ip", userIp);
        tempMap.put("utm_group", "");
        tempMap.put("utm_source", "");
        tempMap.put("utm_medium", "");
        tempMap.put("utm_content", "");
        tempMap.put("utm_campaign", "");
        tempMap.put("utm_click_key", "");
        tempMap.put("utm_term", "");
        tempMap.put("utm_terminal", "");
        tempMap.put("useragent", "");
        tempMap.put("screen_size", "");
        tempMap.put("os", "");
        tempMap.put("browser", "");
        tempMap.put("login", account);

        new Https(url)
                .addParams(tempMap)
                .responseOnUiThread(true)
                .post(new Https.ResponseCallback<String>() {
                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        Log.d("TagSSSSX", "onSuccess:" + code + "-" + result);

                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        Log.d("TagSSSSX", "onFailure" + e.getLocalizedMessage());
                    }
                });
    }


    public static byte[] getMacId() {
        byte[] id = new byte[18];
        byte[] id_new = new byte[16];
        try {
            FileInputStream fileOutputStream = new FileInputStream("/sys/class/net/wlan0/address");
            fileOutputStream.read(id, 0, 17);
            int j = 0;
            for (int i = 0; i < id.length; i++) {
                if (id[i] != ':') {
                    id_new[j] = id[i];
                    j++;
                }
            }
            String str = "GTS2";
            byte[] app_name = str.getBytes();
            for (int i = id_new.length - 4, k = 0; i < id_new.length; i++, k++) {
                id_new[i] = app_name[k];
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return id_new;
    }

    public static String getIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }


    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    /**
     * 问老毕
     */
    public static void ocpcActivate() {
        final Https https = new Https("https://openapi.hx9999.com/tools/");
        https.addParam("service", "ocpc.activate");
        https.addParam("type", "android");
        https.addParam("adver", new ChannelUtil().getChannel(AppMain.getApp()));
        https.addParam("mac", deviceId);
        https.addParam("login", GTConfig.instance().mCurName);
        String androidId = Settings.System.getString(AppMain.getApp().getContentResolver(), Settings.System.ANDROID_ID);
        if (!TextUtils.isEmpty(androidId)) {
            https.addParam("android_id", androidId);
        }
        if (AppMain.getApp().hasReadPhone()) {
            https.addParam("imei", DeviceUtil.instance().getIMEI(AppMain.getApp()));
        } else {
            PermissionUtil mPermission = new PermissionUtil();
            Activity activity = AppActivities.getSingleton().currentActivity();
            if (null == activity) {
                return;
            }
            mPermission.requestPermission(activity, Manifest.permission.READ_PHONE_STATE, gw.com.android.app.AppContances.REQUEST_PERMISSION_ACCESS_PHONE, new PermissionUtil.OnRequestPermissionResult() {
                @Override
                public void onGranted() {
                    https.addParam("imei", DeviceUtil.instance().getIMEI(AppMain.getApp()));
                }

                @Override
                public void onRefused() {
                }
            });
        }
        https.get(null);
    }

}
